layui.define(['laydate', 'laypage', 'layer', 'table', 'carousel', 'upload', 'element', 'slider', 'tree', 'form', 'layedit', 'treeSelect'], function (exports) {


    /**
     * 时间戳格式化函数
     * @param  {string} format    格式
     * @param  {String}    timestamp 要格式化的时间 默认为当前时间
     * @return {string}           格式化的时间字符串
     */
    date = function (format, timestamp) {
        var a, jsdate = ((timestamp) ? new Date(timestamp * 1000) : new Date());
        var pad = function (n, c) {
            if ((n = n + "").length < c) {
                return new Array(++c - n.length).join("0") + n;
            } else {
                return n;
            }
        };
        var txt_weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
        var txt_ordin = {1: "st", 2: "nd", 3: "rd", 21: "st", 22: "nd", 23: "rd", 31: "st"};
        var txt_months = ["", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
        var f = {
            // Day
            d: function () {
                return pad(f.j(), 2)
            },
            D: function () {
                return f.l().substr(0, 3)
            },
            j: function () {
                return jsdate.getDate()
            },
            l: function () {
                return txt_weekdays[f.w()]
            },
            N: function () {
                return f.w() + 1
            },
            S: function () {
                return txt_ordin[f.j()] ? txt_ordin[f.j()] : 'th'
            },
            w: function () {
                return jsdate.getDay()
            },
            z: function () {
                return (jsdate - new Date(jsdate.getFullYear() + "/1/1")) / 864e5 >> 0
            },

            // Week
            W: function () {
                var a = f.z(), b = 364 + f.L() - a;
                var nd2, nd = (new Date(jsdate.getFullYear() + "/1/1").getDay() || 7) - 1;
                if (b <= 2 && ((jsdate.getDay() || 7) - 1) <= 2 - b) {
                    return 1;
                } else {
                    if (a <= 2 && nd >= 4 && a >= (6 - nd)) {
                        nd2 = new Date(jsdate.getFullYear() - 1 + "/12/31");
                        return date("W", Math.round(nd2.getTime() / 1000));
                    } else {
                        return (1 + (nd <= 3 ? ((a + nd) / 7) : (a - (7 - nd)) / 7) >> 0);
                    }
                }
            },

            // Month
            F: function () {
                return txt_months[f.n()]
            },
            m: function () {
                return pad(f.n(), 2)
            },
            M: function () {
                return f.F().substr(0, 3)
            },
            n: function () {
                return jsdate.getMonth() + 1
            },
            t: function () {
                var n;
                if ((n = jsdate.getMonth() + 1) == 2) {
                    return 28 + f.L();
                } else {
                    if (n & 1 && n < 8 || !(n & 1) && n > 7) {
                        return 31;
                    } else {
                        return 30;
                    }
                }
            },

            // Year
            L: function () {
                var y = f.Y();
                return (!(y & 3) && (y % 1e2 || !(y % 4e2))) ? 1 : 0
            },
            //o not supported yet
            Y: function () {
                return jsdate.getFullYear()
            },
            y: function () {
                return (jsdate.getFullYear() + "").slice(2)
            },

            // Time
            a: function () {
                return jsdate.getHours() > 11 ? "pm" : "am"
            },
            A: function () {
                return f.a().toUpperCase()
            },
            B: function () {
                // peter paul koch:
                var off = (jsdate.getTimezoneOffset() + 60) * 60;
                var theSeconds = (jsdate.getHours() * 3600) + (jsdate.getMinutes() * 60) + jsdate.getSeconds() + off;
                var beat = Math.floor(theSeconds / 86.4);
                if (beat > 1000) beat -= 1000;
                if (beat < 0) beat += 1000;
                if ((String(beat)).length == 1) beat = "00" + beat;
                if ((String(beat)).length == 2) beat = "0" + beat;
                return beat;
            },
            g: function () {
                return jsdate.getHours() % 12 || 12
            },
            G: function () {
                return jsdate.getHours()
            },
            h: function () {
                return pad(f.g(), 2)
            },
            H: function () {
                return pad(jsdate.getHours(), 2)
            },
            i: function () {
                return pad(jsdate.getMinutes(), 2)
            },
            s: function () {
                return pad(jsdate.getSeconds(), 2)
            },
            //u not supported yet

            // Timezone
            //e not supported yet
            //I not supported yet
            O: function () {
                var t = pad(Math.abs(jsdate.getTimezoneOffset() / 60 * 100), 4);
                if (jsdate.getTimezoneOffset() > 0) t = "-" + t; else t = "+" + t;
                return t;
            },
            P: function () {
                var O = f.O();
                return (O.substr(0, 3) + ":" + O.substr(3, 2))
            },
            //T not supported yet
            //Z not supported yet

            // Full Date/Time
            c: function () {
                return f.Y() + "-" + f.m() + "-" + f.d() + "T" + f.h() + ":" + f.i() + ":" + f.s() + f.P()
            },
            //r not supported yet
            U: function () {
                return Math.round(jsdate.getTime() / 1000)
            }
        };

        return format.replace(/[\]?([a-zA-Z]/g, function (t, s) {
            if (t != s) {
                // escaped
                ret = s;
            } else if (f[s]) {
                // a date function exists
                ret = f[s]();
            } else {
                // nothing special
                ret = s;
            }
            return ret;
        });
    }


    /**
     *  工具类构造函数
     * @constructor
     */
    var Util = {

        laydate: layui.laydate,//日期
        layer: layer,//日期
        laypage: layui.laypage,//分页
        table: layui.table,//表格
        upload: layui.upload,//上传
        element: layui.element,//元素操作
        slider: layui.slider,//滑块
        tree: layui.tree,//滑块
        form: layui.form,//表单
        layedit: layui.layedit,//富文本编辑器 
        treeSelect: layui.treeSelect,

        actionMap: {
            'del': 'del',
            'add': 'add',
            'edit': 'edit'
        },

        ajax: function (url, data, success, cache, alone, async, type, dataType, error, opt) {
            var type = type || 'post';//请求类型
            var dataType = dataType;
            var async = async || true;//异步请求
            var alone = alone || false;//独立提交（一次有效的提交）
            var cache = cache || false;//浏览器历史缓存
            var ajaxStatus = true;//浏览器历史缓存

            var success = success || function (data) {
                setTimeout(function () {
                    layer.msg(data.msg);//通过layer插件来进行提示信息
                }, 500);
                if (data.status) {//服务器处理成功
                    setTimeout(function () {
                        if (data.url) {
                            location.replace(data.url);
                        } else {
                            location.reload(true);
                        }
                    }, 500);
                } else {//服务器处理失败
                    if (alone) {//改变ajax提交状态
                        ajaxStatus = true;
                    }
                }
            };
            var error = error || function (data) {

                layer.closeAll('loading');
                setTimeout(function () {
                    if (data.status == 404) {
                        layer.msg('请求失败，请求未找到');
                    } else if (data.status == 503) {
                        layer.msg('请求失败，服务器内部错误');
                    } else {
                        layer.msg('请求失败,网络连接超时');
                    }
                    ajaxStatus = true;
                }, 100);
            };
            /*判断是否可以发送请求*/
            if (!ajaxStatus) {
                return false;
            }
            ajaxStatus = false;//禁用ajax请求
            /*正常情况下1秒后可以再次多个异步请求，为true时只可以有一次有效请求（例如添加数据）*/
            if (!alone) {
                setTimeout(function () {
                    ajaxStatus = true;
                }, 100);
            }

            var _opt = $.extend({
                'url': url,
                'data': data,
                'type': type,
                'cache': cache,
                'dataType': dataType,
                'async': async,
                'success': success,
                'error': error,
                'jsonpCallback': 'jsonp' + (new Date()).valueOf().toString().substr(-4),
                'beforeSend': function () {
                    layer.msg('加载中', {
                        icon: 16,
                        shade: 0.01
                    });
                }
            }, opt);
            $.ajax(_opt);
        },

        // submitAjax(post方式提交)
        submitAjax: function (form, success, cache, alone) {
            cache = cache || true;
            var form = $(form);
            var url = form.attr('action');
            var data = form.serialize();
            this.ajax(url, data, success, cache, alone, false, 'post', 'json');
        },
        // ajax提交(post方式提交)
        post: function (url, data, success, cache, alone) {
            this.ajax(url, data, success, cache, alone, false, 'post', 'json');
        },

        // ajax提交(get方式提交)
        get: function (url, success, cache, alone) {
            this.ajax(url, {}, success, cache, alone, false, 'get', 'json');
        },

        // jsonp跨域请求(get方式提交)
        jsonp: function (url, success, cache, alone) {
            this.ajax(url, {}, success, cache, alone, false, 'get', 'jsonp');
        },
        send: function (url, data, opt) {
            this.ajax(url, data, opt.success, opt.cache, opt.alone, opt.async, opt.type, opt.contentType, opt.error, opt);
        },


        getTime: function (time, fmt) {
            return date(fmt || 'Y-m-d H:i:s', new String(time));
        },

        // templateProxy
        templateProxy: function (htmlUrl, data, opt) {

            var self = this;

            var html = this.getTemPlates(htmlUrl);

            var _opt = $.extend({
                    type: 1
                    , offset: 'auto'
                    , id: 'editAttrs'
                    , content: $.templates(html).render(data)
                    , area: ['500px', '300px']
                    , btn: ['确定', '关闭']
                    , btnAlign: 'c' //按钮居中
                    , shade: 0 //不显示遮罩
                    , yes: function (index, e) {
                        if (opt.confirm && $.isFunction(opt.confirm)) {
                            opt.confirm.call(this, self.getFormData($(e).find('form')), e, layer)
                        }
                    }
                    ,
                    btn2: function (index, e) {
                        if (opt.cancel && $.isFunction(opt.cancel)) {
                            opt.cancel.call(this, index, e, layer);
                        }
                    }
                }, opt
            );
            layer.open(_opt);
        },
        /**
         * getFormData
         * @param form
         */
        getFormData: function (form) {
            var values = {};
            var _form = $(form);

            if (!_form.length) {
                return values;
            }

            var data = _form.serializeArray();

            for (var item in data) {
                values[data[item].name] = data[item].value;
            }

            return values;
        },
        /**
         * 获取前端html模板方法<!注意 模板命名已模块名开头,请求路径为resources/moduleName/*.html>
         *
         * @param {[type]}
         *            [url] [模板资源名称]
         * @return {[type]} [description]
         */
        getTemPlates: function (url) {
            var self = this;
            var templateHtmlTpl = null;
            self.send(url, null, {
                type: "get", //静态资源使用get方式请求
                dataType: "html",
                contentType: "application/x-www-form-urlencoded;charset=UTF-8",
                async: false,
                success: function (resp) {
                    templateHtmlTpl = resp;
                }
            });
            return templateHtmlTpl;
        },

        selected: function () {
            var model = location.href;
            var $model = $('.models[href="' + model.slice(model.lastIndexOf(appUrl)) + '"]');
            $model.closest('dd').addClass('layui-this').siblings('.dd').removeClass("layui-this");
            var nav = $model.closest(".layui-nav-item");
            nav.addClass("layui-nav-itemed").siblings('.layui-nav-item').removeClass("layui-nav-itemed");
        }
    };

    exports('util', Util);
});